<template>
  <div class="finance-page">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <div class="stat-card income">
          <div class="stat-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ formatMoney(stats.totalIncome) }}</div>
            <div class="stat-label">总收入</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card expense">
          <div class="stat-icon">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ formatMoney(stats.totalExpense) }}</div>
            <div class="stat-label">总支出</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card profit">
          <div class="stat-icon">
            <el-icon><Wallet /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ formatMoney(stats.totalProfit) }}</div>
            <div class="stat-label">净利润</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card count">
          <div class="stat-icon">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.recordCount }}</div>
            <div class="stat-label">记录数量</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <el-col :span="12">
        <div class="card">
          <h3>收支趋势</h3>
          <div ref="trendChartRef" style="height: 300px;"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="card">
          <h3>收支分类</h3>
          <div ref="categoryChartRef" style="height: 300px;"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 财务记录表格 -->
    <div class="card">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增记录
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出报表
          </el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-select
            v-model="searchForm.type"
            placeholder="收支类型"
            clearable
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="收入" value="income" />
            <el-option label="支出" value="expense" />
          </el-select>
          <el-select
            v-model="searchForm.category"
            placeholder="分类"
            clearable
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="律师费" value="lawyer_fee" />
            <el-option label="咨询费" value="consulting_fee" />
            <el-option label="办公费用" value="office_expense" />
            <el-option label="差旅费" value="travel_expense" />
            <el-option label="其他" value="other" />
          </el-select>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px; margin-right: 10px"
            @change="handleSearch"
          />
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索描述"
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === 'income' ? 'success' : 'danger'">
              {{ row.type === 'income' ? '收入' : '支出' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            {{ getCategoryText(row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            <span :class="row.type === 'income' ? 'text-success' : 'text-danger'">
              {{ row.type === 'income' ? '+' : '-' }}{{ formatMoney(row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="caseTitle" label="关联案件" width="150" show-overflow-tooltip />
        <el-table-column prop="contractTitle" label="关联合同" width="150" show-overflow-tooltip />
        <el-table-column prop="date" label="日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.date, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 财务记录表单对话框 -->
    <FinanceForm
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { getFinanceList, deleteFinanceRecord, getFinanceStats, getFinanceTrend, exportFinanceReport } from '@/api/finance'
import { formatDate, formatMoney, downloadFile } from '@/utils'
import type { FinanceRecord, Pagination } from '@/types'
import FinanceForm from './components/FinanceForm.vue'

const loading = ref(false)
const selectedIds = ref<string[]>([])
const tableData = ref<FinanceRecord[]>([])
const formVisible = ref(false)
const formData = ref<Partial<FinanceRecord>>({})
const trendChartRef = ref<HTMLElement>()
const categoryChartRef = ref<HTMLElement>()

const stats = reactive({
  totalIncome: 0,
  totalExpense: 0,
  totalProfit: 0,
  recordCount: 0
})

const searchForm = reactive({
  keyword: '',
  type: '',
  category: '',
  dateRange: null as any
})

const pagination = reactive<Pagination>({
  current: 1,
  pageSize: 20,
  total: 0
})

// 获取财务记录列表
const fetchFinanceList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    delete params.dateRange
    
    const data = await getFinanceList(params)
    tableData.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取财务记录失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const data = await getFinanceStats()
    Object.assign(stats, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 收支趋势图
  if (trendChartRef.value) {
    const trendChart = echarts.init(trendChartRef.value)
    try {
      const trendData = await getFinanceTrend({ period: 'month', count: 12 })
      trendChart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['收入', '支出'] },
        xAxis: { type: 'category', data: trendData.months },
        yAxis: { type: 'value' },
        series: [
          {
            name: '收入',
            type: 'line',
            data: trendData.income,
            itemStyle: { color: '#67c23a' }
          },
          {
            name: '支出',
            type: 'line',
            data: trendData.expense,
            itemStyle: { color: '#f56c6c' }
          }
        ]
      })
    } catch (error) {
      console.error('获取趋势数据失败:', error)
    }
  }
  
  // 分类饼图
  if (categoryChartRef.value) {
    const categoryChart = echarts.init(categoryChartRef.value)
    categoryChart.setOption({
      tooltip: { trigger: 'item' },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: [
            { value: stats.totalIncome * 0.6, name: '律师费' },
            { value: stats.totalIncome * 0.3, name: '咨询费' },
            { value: stats.totalIncome * 0.1, name: '其他收入' }
          ]
        }
      ]
    })
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchFinanceList()
}

// 选择变化
const handleSelectionChange = (selection: FinanceRecord[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增记录
const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}

// 编辑记录
const handleEdit = (row: FinanceRecord) => {
  formData.value = { ...row }
  formVisible.value = true
}

// 删除记录
const handleDelete = async (row: FinanceRecord) => {
  try {
    await ElMessageBox.confirm(`确定要删除这条财务记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteFinanceRecord(row.id)
    ElMessage.success('删除成功')
    fetchFinanceList()
    fetchStats()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await Promise.all(selectedIds.value.map(id => deleteFinanceRecord(id)))
    ElMessage.success('批量删除成功')
    fetchFinanceList()
    fetchStats()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 导出报表
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    delete params.dateRange
    
    const blob = await exportFinanceReport(params)
    downloadFile(URL.createObjectURL(blob), `财务报表_${formatDate(new Date(), 'YYYY-MM-DD')}.xlsx`)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchFinanceList()
  fetchStats()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchFinanceList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchFinanceList()
}

// 获取分类文本
const getCategoryText = (category: string) => {
  const textMap: Record<string, string> = {
    lawyer_fee: '律师费',
    consulting_fee: '咨询费',
    office_expense: '办公费用',
    travel_expense: '差旅费',
    other: '其他'
  }
  return textMap[category] || category
}

onMounted(() => {
  fetchFinanceList()
  fetchStats()
  initCharts()
})
</script>

<style lang="scss" scoped>
.finance-page {
  .stats-cards {
    margin-bottom: 20px;
    
    .stat-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      display: flex;
      align-items: center;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        .el-icon {
          font-size: 24px;
          color: #fff;
        }
      }
      
      .stat-content {
        flex: 1;
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 4px;
        }
        
        .stat-label {
          color: #909399;
          font-size: 14px;
        }
      }
      
      &.income {
        .stat-icon {
          background: #67c23a;
        }
        .stat-value {
          color: #67c23a;
        }
      }
      
      &.expense {
        .stat-icon {
          background: #f56c6c;
        }
        .stat-value {
          color: #f56c6c;
        }
      }
      
      &.profit {
        .stat-icon {
          background: #409eff;
        }
        .stat-value {
          color: #409eff;
        }
      }
      
      &.count {
        .stat-icon {
          background: #e6a23c;
        }
        .stat-value {
          color: #e6a23c;
        }
      }
    }
  }
  
  .charts-section {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .text-success {
    color: #67c23a;
  }
  
  .text-danger {
    color: #f56c6c;
  }
}
</style>
